<template>
	<view class="list">
		<view class="top">
			<!-- 搜索框 -->
			<view class="searchbox">
				<uni-search-bar v-model="myparams.query" @confirm="myconfirm" cancelButton="none"></uni-search-bar>
			</view>

			<!-- tab栏 -->
			<view class="tabs">
				<view class="tab-item" @click="changeIndex(index)" :class="{active: activeIndex === index}"
					v-for="(item, index) in tabs" :key="index">
					{{ item }}
				</view>
			</view>
		</view>

		<!-- 商品列表数据 -->
		<view class="goodslist">
			<view @click="toDetail(item.goods_id)" v-for="(item, index) in searchList" :key="index">
				<my-goods :item="item"></my-goods>
			</view>
		</view>
	</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				tabs: ['综合', '销量', '价格'],
				activeIndex: 0,
				// 请求列表的参数
				myparams: {
					query: '',
					pagenum: 1,
					pagesize: 10
				},
				// 搜索数据源
				searchList: [],
				// 总数
				total: 0,
				isSending: false

			};
		},
		methods: {
			myconfirm() {
				// 重置数据源
				this.myparams.pagenum = 1
				this.searchList = []
				this.total = 0
				this.isSending = false
				// 重新请求数据
				this.getSearchList()
			},
			toDetail(id) {
				uni.navigateTo({
					url: `/pages/goods_detail/main?goods_id=${id}`
				})
			},
			// 获取搜索列表数据
			async getSearchList(bool) {
				// 将状态设置为正在发送
				this.isSending = true
				const {
					data: res
				} = await uni.$http.get('/api/public/v1/goods/search', this.myparams)
				// console.log(res);
				// 判断
				if (res.meta.status !== 200) return uni.$showMsg()
				// 保存数据
				this.searchList = [...this.searchList, ...res.message.goods]
				this.total = res.message.total
				// 将状态设置为发送完成
				this.isSending = false
				if (bool) uni.stopPullDownRefresh()
			},

			changeIndex(index) {
				this.activeIndex = index
			}
		},
		onLoad(options) {
			// 得到传入的参数
			this.myparams.query = options.key
			// 调用获取搜索列表的数据
			this.getSearchList()
		},
		onReachBottom() {
			// 判断数据源是否加载完毕
			if (this.searchList.length === this.total) return uni.showToast({
				title: '数据源加载完毕',
				// 默认带图标，带图标时最多展示7个字，无官方解决方法。
				// title: '数据源加载完毕，我发展得更加完善的时候，给你展示更多内容',
				// icon: 'none'
			})
			
			// 判断请求是否存在发送
			if (this.isSending) return
			// 将当前页++
			this.myparams.pagenum += 1,
				this.getSearchList()
		},
		// 下拉会触发的函数
		onPullDownRefresh() {
			// 重置数据源
			this.myparams.pagenum = 1
			this.searchList = []
			this.total = 0
			this.isSending = false
			// 重新请求数据
			this.getSearchList(true)
		}
	}
</script>

<style lang="scss">
	.list {
		.top {
			position: sticky;
			left: 0;
			top: 0;
		}

		.searchbox {
			background-color: #eee;
		}

		.tabs {
			display: flex;
			height: 100rpx;
			border-bottom: 1px solid #f2f2f2;
			background-color: #fff;

			.tab-item {
				flex: 1;
				text-align: center;
				line-height: 100rpx;
				color: #5d5d5d;

				&.active {
					color: #fe4d66;
				}
			}
		}

		.goodslist {
			padding: 0 20rpx;

		}
	}
</style>
